package a04_字符串;

/**
 * <p>
 * a02_反转字符串2
 * </p>
 *
 * @author flyduck
 * @since 2024-07-09
 */
public class a02_反转字符串2复习1 {
    public static void main(String[] args) {
        reverseStr("abcdefg", 2);
    }


    public static String reverseStr(String source, int k) {
        char[] chars = source.toCharArray();
        //abcdefg k=2
        //i=0 a
        //i=4 e
        for (int i = 0; i < chars.length; i = i + 2 * k) {
            //反转的是 i -> i+k-1
            if(i + k - 1 <= chars.length - 1){
                swap(chars,i,i+k-1);
            }else {
                swap(chars,i,chars.length - 1);
            }
        }
        return new String(chars);
    }

    private static void swap(char[] chars, int leftIndex, int rightIndex) {
        while (leftIndex < rightIndex) {
            char temp = chars[leftIndex];
            chars[leftIndex] = chars[rightIndex];
            chars[rightIndex] = temp;
            leftIndex++;
            rightIndex--;
        }
    }

}
